﻿
Public Class config
    Public Shared reserveJobInfoSeconds As Int64 = configNaming.defaultValue.localrun.reserveJobInfoSeconds
End Class

Public Module localrun
    Public Const defaultConfigfile As String = "localrun.ini"
    Public Const delegate_path As String = "delegates"
    Private _jobmgr As jobmgr_t = Nothing
    Private WithEvents cm As configMonitor = Nothing
    Private server As lrserver = Nothing

    Private Sub initial()
        config.reserveJobInfoSeconds = cm.parameter(configNaming.localrun.name, _
                                                    configNaming.localrun.reserveJobInfoSeconds, _
                                                    configNaming.defaultValue.localrun.reserveJobInfoSeconds)
    End Sub

    Public Function jobmgr() As jobmgr_t
        assert(Not _jobmgr Is Nothing)
        Return _jobmgr
    End Function

    Private Sub startService()
        If _jobmgr Is Nothing Then
            _jobmgr = New jobmgr_t()
        End If
        If server Is Nothing Then
            server = New lrserver()
        End If
        server.start()
    End Sub

    Private Sub shutdownService()
        server.stop()
    End Sub

    Private Sub monitor()
        registerConsoleExtHandle()

        While Not consoleExtSignal()
            If server.health() Then
                sleep(1000)
            Else
                Exit While
            End If
        End While

        If Not consoleExtSignal() Then
            If Not server.health() Then
                raiseError("server engender an error, start shutdown.", errorHandle.errorType.exclamation)
            End If
        Else
            raiseError("terminating signal caught, start shutdown.")
        End If
    End Sub

    Private Sub unhandledException(ByVal ex As Exception)
        shutdownService()
    End Sub

    Public Sub main(ByVal args() As String)
        dpslib.consoleApplicationStartParameters.unhandledExceptionhandler = AddressOf unhandledException
        dpslib.startmain()
        Dim configfile As String = Nothing
        If args.Length() = 0 Then
            configfile = defaultConfigfile
        Else
            configfile = args(0)
        End If
        cm = New configMonitor()
        assert(cm.open(configfile))
        initial()

        startService()
        monitor()
        shutdownService()
        finishmain()
    End Sub

    Private Sub cm_configChanged() Handles cm.configChanged
        initial()
    End Sub
End Module
